<?php
/**
 * Created by PhpStorm.
 * User: s.utkin
 * Date: 09.01.2015
 * Time: 18:44
 */

namespace Pinenut\Queue;


abstract class Job extends \Action {

	protected $config = [
		'queueClassName' => '',
		'dispatcherClassName' => '',
		'workersConfigClassName' => '',

		'dequeueStep' => 10,
		'jobSleepingTime' => 100000,
		'jobLiveTime' => 60,
	];

	/**
	 *    public function options()
	 *    {
	 *        return [
	 *            'queueClassName' => '\Class\Name',
	 *            'dispatcherClassName' => '\Class\Name',
	 *            'workersConfigClassName' => '\Class\Name',
	 *        ];
	 *    }
	 * @return mixed
	 */
	abstract public function options();


	/**
	 * Демон очереди уведомлений
	 */
	protected function run()
	{
		$this->config = array_merge($this->config, $this->options());

 		$this->response->noRender(true);
 		$this->response->noCache(true);
		
		$startTime = time();

		# Создаем диспетчера
		$dispatcherClassName = $this->config['dispatcherClassName'];
		$dispatcher = new $dispatcherClassName($this->config['workersConfigClassName']);

		# Создаем очередь
		$queueClassName = $this->config['queueClassName'];
		$queueModel = new $queueClassName();
		while (true) {
		    # достаем список задач из очереди и отдаем их диспетчеру на выполнение 
			$dispatcher->run((array)$queueModel->dequeue($this->config['dequeueStep']));

			usleep((int)$this->config['jobSleepingTime']);

			$currentTime = time();

			if (($currentTime - $startTime) > (int)$this->config['jobLiveTime']) {
				break;
			}
		}
	}
} 